package com.coolweather.android;

import static com.coolweather.android.constants.Constants.PROVINCE_URL;

import android.app.ProgressDialog;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.coolweather.android.constants.Constants;
import com.coolweather.android.databinding.ChooseAreaBinding;
import com.coolweather.android.db.City;
import com.coolweather.android.db.Country;
import com.coolweather.android.db.Province;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {

    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String COUNTRY = "country";
    ChooseAreaBinding binding;



    public static final int LEVEL_PROVINCE=0;
    public static final int LEVEL_CITY=1;
    public static final int LEVEL_COUNTRY=2;
    private int currentlevel=LEVEL_PROVINCE;

    List<Province> provinceList;
    List<City> cityList;
    List<Country> countryList;
    private Province selectedProvice;
    private City selectedCity;

    List<String> datalist=new ArrayList<>();
    ArrayAdapter<String> adapter;


ProgressDialog progressDialog;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = ChooseAreaBinding.inflate(inflater,container,false);

        adapter=new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1,datalist);
        binding.listView.setAdapter(adapter);


        return binding.getRoot();
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        binding.listView.setOnItemClickListener((adapterView, view, position, id) -> {
            if(currentlevel==LEVEL_PROVINCE){
                selectedProvice=provinceList.get(position);
                queryCities();
            }else if(currentlevel==LEVEL_CITY){
                selectedCity=cityList.get(position);
                queryCounties();
            }else if(currentlevel==LEVEL_COUNTRY){
                Country country = countryList.get(position);
                String spot=String.format("%s|%s|%s",
                selectedProvice.getProvinceName(),
                        selectedCity.getCityName(),
                        country.getCountryName());
                String location= country.getWeatherId().substring(2);
                Log.d("test", "onActivityCreated: "+spot+"|"+location);
                Intent intent=new Intent(getActivity(),WeatherActivity.class);
                intent.putExtra("spot",spot);
                intent.putExtra("location",location);
                startActivity(intent);
                getActivity().finish();


            }
        });
        binding.backButton.setOnClickListener(v->{
            if(currentlevel==LEVEL_CITY){
                queryProvinces();
            }else if(currentlevel==LEVEL_COUNTRY){
                queryCities();
            }
        });
        queryProvinces();
    }

    private void queryCounties() {
        binding.titleText.setText(selectedProvice.getProvinceName()+":"+selectedCity.getCityName());
        binding.backButton.setVisibility(View.VISIBLE);

        countryList = LitePal.where("cityId=?",
                String.valueOf(selectedCity.getId())).find(Country.class);

        if(countryList.size()>0){
            datalist.clear();
            countryList.forEach(item->{
                datalist.add(item.getCountryName());

            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentlevel=LEVEL_COUNTRY;

        }else{
            String url=PROVINCE_URL+"/"+selectedProvice.getProvinceCode()+"/"+selectedCity.getCityCode();
            queryFroServer(url, COUNTRY);


        }


    }


    private void queryCities() {
        binding.titleText.setText(selectedProvice.getProvinceName());
        binding.backButton.setVisibility(View.VISIBLE);

        cityList = LitePal.where("provinceId=?",
                String.valueOf(selectedProvice.getId())).find(City.class);

        if(cityList.size()>0){
            datalist.clear();
            cityList.forEach(item->{
                datalist.add(item.getCityName());

            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentlevel=LEVEL_CITY;

        }else{
            String url=PROVINCE_URL+"/"+selectedProvice.getProvinceCode();
            queryFroServer(url, CITY);


        }


    }

    private void queryProvinces() {
        binding.titleText.setText("中国(CHINA)");
        binding.backButton.setVisibility(View.GONE);

        provinceList = LitePal.findAll(Province.class);
        if(provinceList.size()>0){
            datalist.clear();
            provinceList.forEach(item->{
                datalist.add(item.getProvinceName());

            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentlevel=LEVEL_PROVINCE;

        }else{
           queryFroServer(PROVINCE_URL, PROVINCE);


        }

    }

    private void queryFroServer(String url, String type) {
        Log.d("test",url);
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
               getActivity().runOnUiThread(()->{
                   Toast.makeText(getContext(), "访问网络失败", Toast.LENGTH_SHORT).show();
                   closeProgressDialog();
               });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String strJson = response.body().string();
                Log.d("test", "onResponse: "+strJson);
                boolean result=false;
                if(PROVINCE.equals(type)){
                  result =  Utility.handleProvinceResponse(strJson);

                }else if(CITY.equals(type)){
                    result =Utility.handleCityResponse(strJson,selectedProvice.getId());
                }else if(COUNTRY.equals(type)){
                    result =Utility.handleCountryResponse(strJson,selectedCity.getId());
                }
                if(result){
                    if(PROVINCE.equals(type)){
                        getActivity().runOnUiThread(()->{
                           queryProvinces();
                        });
                    }else if(CITY.equals(type)){
                        getActivity().runOnUiThread(()->{
                            queryCities();
                        });
                    }
                    else if(COUNTRY.equals(type)){
                        getActivity().runOnUiThread(()->{
                            queryCounties();
                        });

                    }
                    closeProgressDialog();
                }else {
                    getActivity().runOnUiThread(()->{
                        Toast.makeText(getContext(),
                                "数据访问失败",Toast.LENGTH_SHORT).show();
                        closeProgressDialog();
                    });
                }

            }
        });
    }

    private void closeProgressDialog() {
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    private void showProgressDialog() {
        if(progressDialog==null){
            progressDialog=new ProgressDialog(getContext());
            progressDialog.setMessage("正在访问，请稍后");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }
}
